package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 长平居士 - rolfcui@outlook.com
 * @description ${什么模块下的什么功能}
 * @date 2022/7/31 17:56
 */
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender sender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();

        try {
            // 0. 验证数据
            // 判空
            registerRequest.requestCheck();
            // 查重复
            validUserNameRepeat(registerRequest);
            validUserEmailRepeat(registerRequest);

            // 1. 向用户表中插入数据
            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            member.setEmail(registerRequest.getEmail());
            // 密码要加密！
            // member.setPassword(registerRequest.getUserPwd());
            String userPassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
            member.setPassword(userPassword);
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            member.setFile("https://www.matools.com/img/home/gif/default_gif.gif");
            int effectRows = memberMapper.insert(member);
            if (effectRows != 1) {
                response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            // 2. 向用户验证表中插入数据
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");

            int rows = userVerifyMapper.insert(userVerify);
            if (rows != 1) {
                response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            // 3. 发送激活邮件
            // TODO 会消息中间件后修改
            sendEmail(uuid, registerRequest);

            // 打印日志并返回结果
            log.info("注册成功，参数 request 为：{}", JSON.toJSONString(registerRequest));
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }


        return response;
    }

    @Override
    public UserVerifyResponse verify(UserVerifyRequest verifyRequest) {
        UserVerifyResponse response = new UserVerifyResponse();

        // 更新 member 表
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", verifyRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)) {
            response.setCode(UserRetCode.USER_INFOR_UPDATE_FAIL.getCode());
            response.setMsg(UserRetCode.USER_INFOR_UPDATE_FAIL.getMessage());
            return response;
        }

        Member member = members.get(0);
        member.setIsVerified("Y");
        memberMapper.updateByPrimaryKey(member);

        // 更新验证表
        Example vExample = new Example(UserVerify.class);
        vExample.createCriteria().andEqualTo("username", verifyRequest.getUserName());
        List<UserVerify> verifies = userVerifyMapper.selectByExample(vExample);
        if (CollectionUtils.isEmpty(verifies)) {
            response.setCode(UserRetCode.USER_INFOR_UPDATE_FAIL.getCode());
            response.setMsg(UserRetCode.USER_INFOR_UPDATE_FAIL.getMessage());
            return response;
        }

        UserVerify verify = verifies.get(0);
        verify.setIsVerify("Y");
        userVerifyMapper.updateByPrimaryKey(verify);

        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        return response;
    }

    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("changpingjushi@126.com");
        message.setSubject("验证邮件");
        message.setTo(registerRequest.getEmail());
        StringBuilder sb = new StringBuilder();
        sb.append("http://localhost:8099/user/verify?uuid=").append(uuid).append("&userName=").append(registerRequest.getUserName());
        message.setText(sb.toString());
        sender.send(message);
    }

    private void validUserNameRepeat(UserRegisterRequest registerRequest) throws ValidateException {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", registerRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(), UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }

    private void validUserEmailRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("email", registerRequest.getEmail());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(UserRetCode.EMAIL_ALREADY_EXISTS.getCode(), UserRetCode.EMAIL_ALREADY_EXISTS.getMessage());
        }
    }

}
